<template>
  <div class="device-dashboard">
    <!-- 顶部概览区域 -->
    <div class="overview">
      <div class="overview-item">
        <span class="title">设备总数量</span>
        <span class="value">{{ deviceCount.total || 0 }}</span>
      </div>
      <div class="overview-item">
        <span class="title">进行中设备数</span>
        <span class="value">{{ deviceCount.running || 0 }}</span>
      </div>
      <div class="overview-item">
        <span class="title">已停止设备数</span>
        <span class="value">{{ deviceCount.stopped || 0 }}</span>
      </div>
      <div class="overview-item">
        <span class="title">异常设备数</span>
        <span class="value">{{ deviceCount.abnormal || 0 }}</span>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts">
      <div class="chart-item">
        <h3>设备状态分布</h3>
        <div ref="statusPieChart" class="chart" style="width: 400px; height: 300px;"></div>
      </div>
      <div class="chart-item">
        <h3>各设备种类数量</h3>
        <div ref="loadLineChart" class="chart" style="width: 600px; height: 300px;"></div>
      </div>
    </div>

    <!-- 实时监控列表 -->
    <div class="realtime-monitor">
      <h3>实时监控数据</h3>
      <!-- 关键：prop 必须与后端 DeviceResp 的 json 字段严格一致 -->
      <el-table :data="formattedRealtimeData" border style="width: 100%">
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deviceStatusReason" label="设备状态原因" />
        <el-table-column prop="deviceAfterSales" label="设备售后负责人" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElTable, ElTableColumn, ElTag } from 'element-plus';
import { running, realtime } from '@/api/system/device';

// 设备统计数据
const deviceCount = ref({
  total: 0,
  running: 0,
  stopped: 0,
  abnormal: 0,
  smartTerminal: 0,
  edgeGateway: 0,
});

// 实时设备数据
const realtimeData = ref([]);

// 格式化实时数据，确保是数组格式
const formattedRealtimeData = computed(() => {
  return Array.isArray(realtimeData.value) ? realtimeData.value : [];
});

// 轮询定时器
let pollInterval = null;
// 轮询间隔时间（1000毫秒 = 1秒）
const POLL_INTERVAL = 1000;

// 获取设备统计数据
const fetchDeviceCount = async () => {
  try {
    const res = await running();
    if (res && res.code === 0 && res.data) {
      deviceCount.value = res.data;
      updateChartsData();
    } else {
      console.error('设备统计接口异常:', res);
    }
  } catch (error) {
    console.error('获取设备统计数据失败:', error);
  }
};

// 获取实时数据
const fetchRealtimeData = async () => {
  try {
    const res = await realtime();
    if (res && res.code === 0) {
      realtimeData.value = res.data || [];
    } else {
      console.error('实时数据接口报错:', res?.msg || '未知错误');
      realtimeData.value = [];
    }
  } catch (error) {
    console.error('获取实时数据失败:', error);
    realtimeData.value = [];
  }
};

// 更新图表数据
const updateChartsData = () => {
  if (statusPieChart.value) {
    const statusPie = echarts.getInstanceByDom(statusPieChart.value);
    if (statusPie) {
      statusPie.setOption({
        series: [{
          data: [
            { value: deviceCount.value.running, name: '进行中' },
            { value: deviceCount.value.stopped, name: '已停止' },
            { value: deviceCount.value.abnormal, name: '设备异常' },
          ],
        }],
      });
    }
  }

  if (loadLineChart.value) {
    const loadLine = echarts.getInstanceByDom(loadLineChart.value);
    if (loadLine) {
      loadLine.setOption({
        series: [{
          data: [deviceCount.value.smartTerminal, deviceCount.value.edgeGateway],
        }],
      });
    }
  }
};

// 图表引用
const statusPieChart = ref(null);
const loadLineChart = ref(null);

// 初始化图表
const initCharts = async () => {
  await nextTick();
  const statusPie = echarts.init(statusPieChart.value);
  statusPie.setOption({
    title: { text: '', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left' },
    series: [{
      name: '设备状态',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [
        { value: deviceCount.value.running, name: '进行中' },
        { value: deviceCount.value.stopped, name: '已停止' },
        { value: deviceCount.value.abnormal, name: '设备异常' },
      ],
    }],
  });

  const loadLine = echarts.init(loadLineChart.value);
  loadLine.setOption({
    xAxis: { type: 'category', data: ["智能终端", "边缘网关"] },
    yAxis: { type: 'value', name: '设备数量' },
    series: [{
      name: '设备数量',
      type: 'line',
      data: [deviceCount.value.smartTerminal, deviceCount.value.edgeGateway],
      smooth: true,
    }],
  });
};

// 启动1秒轮询
const startPolling = () => {
  stopPolling(); // 先清除旧定时器
  pollInterval = setInterval(async () => {
    await fetchDeviceCount();
    await fetchRealtimeData();
    console.log('1秒轮询更新数据', new Date().toLocaleTimeString());
  }, POLL_INTERVAL);
};

// 停止轮询
const stopPolling = () => {
  if (pollInterval) {
    clearInterval(pollInterval);
    pollInterval = null;
  }
};

// 生命周期钩子
onMounted(async () => {
  await fetchDeviceCount();
  await fetchRealtimeData();
  await initCharts();
  startPolling(); // 组件挂载后启动1秒轮询
});

onUnmounted(() => {
  stopPolling(); // 组件卸载时停止轮询，避免内存泄漏
});

// 状态标签类型映射
const getStatusTagType = (status) => {
  switch (status) {
    case '进行中': return 'success';
    case '设备异常': return 'danger';
    case '已停止': return 'warning';
    default: return 'info';
  }
};
</script>

<style scoped>
/* 样式保持不变，无需修改 */
.device-dashboard {
  padding: 20px;
  max-width: 1920px;
  margin: 0 auto;
}

.overview {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  gap: 10px;
}

.overview-item {
  flex: 1;
  min-width: 120px;
  text-align: center;
  margin-bottom: 10px;
}

.overview-item .title { font-size: 14px; color: #666; margin-bottom: 8px; }
.overview-item .value { font-size: 20px; font-weight: bold; color: #333; }

.charts { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 20px; }
.chart-item { background-color: #d1d7dc; padding: 30px; border-radius: 20px; box-shadow: 0 0 15px rgba(0, 0, 0, 0.1); flex: 1; min-width: 300px; }
.chart-item h3 { margin-bottom: 20px; font-size: 20px; font-weight: bold; }
.chart { width: 100% !important; height: 300px !important; }

.realtime-monitor { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }
.realtime-monitor h3 { margin-bottom: 10px; font-size: 16px; font-weight: bold; }

@media (max-width: 768px) {
  .charts { flex-direction: column; }
  .chart-item { min-width: auto; }
}
</style>